const jwt = require('jsonwebtoken');

const JWT_SECRET = 'admin_secret';  // 管理后台专用密钥，建议放在环境变量中

// 管理后台白名单路由
const adminWhiteList = [
  '/api/admin/auth/login',
];

const adminAuthMiddleware = (req, res, next) => {
  // 如果是白名单路由，直接通过
  const fullPath = `/api${req.path}`;
  if (adminWhiteList.includes(fullPath)) {
    return next();
  }

  const token = req.headers.authorization?.split(' ')[1];
  
  if (!token) {
    return res.status(401).json({
      code:500,
      message: '未登录或登录已过期11'
    });
  }

  try {
    const decoded = jwt.verify(token, JWT_SECRET);
    // 验证是否是管理员
    if (decoded.role !== 'admin') {
      return res.status(403).json({
        code:500,
        message: '无权访问'
      });
    }
    req.user = decoded;
    next();
  } catch (error) {
    return res.status(401).json({
      code:500,
      message: '未登录或登录已过期22'
    });
  }
};

module.exports = adminAuthMiddleware; 